package com.hbw.pinyin.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.hbw.pinyin.App;
import com.hbw.pinyin.db.dao.DBRecordDao;
import com.hbw.pinyin.db.dao.DaoMaster;
import com.hbw.pinyin.db.dao.DaoSession;

import org.greenrobot.greendao.database.Database;

public class DBFactory {
    private static final String DB_NAME = "db";
    private static DaoMaster.DevOpenHelper devOpenHelper;
    private static DaoSession sharedSession;

    public static DaoSession sharedSessions() {
        if (devOpenHelper == null) {
            devOpenHelper = new WaferDevOpenHelper(App.getApp(), DB_NAME, null);
        }
        if (sharedSession == null) {
            Database db = devOpenHelper.getWritableDb();
            DaoMaster daoMaster = new DaoMaster(db);
            sharedSession = daoMaster.newSession();
        }
        return sharedSession;
    }

    public static class WaferDevOpenHelper extends DaoMaster.DevOpenHelper {

        public final int DB_VERSION_1_0 = 1;

        public WaferDevOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
            super(context, name, factory);
        }

        @Override
        public void onUpgrade(Database db, int oldVersion, int newVersion) {
            // 数据库表升级
            if (oldVersion < DB_VERSION_1_0) {
                DBRecordDao.dropTable(db, true);
            }
            DaoMaster.createAllTables(db, true);
        }
    }

    public static void clear() {
        if (sharedSession != null) {
            sharedSession.clear();
        }
        if (devOpenHelper != null) {
            devOpenHelper.close();
        }
    }
}
